import React, { useCallback, useEffect, useState } from 'react'
import { View, Text, Input } from '@tarojs/components'
import SurveyHeader from './SurveyHeader'
import styles from './SurveyNumber.module.scss'

const SurveyNumber = ({
  data, language, onChange, submitted, ordinal, questionType, onFocusFun, onBlurFun
}) => {
  const { AnswerNum, AnswerRange, AnswerUnit } = data
  const [text, setText] = useState(AnswerNum || '')

  const onChangeText = useCallback(e => {
    let val = e.detail.value
    val = (String(val)).replace(/^0(?=[0-9])/g, '')
    if (AnswerRange) {
      if (Number(val) > AnswerRange[1]) {
        val = String(AnswerRange[1])
      } else if (Number(val) < AnswerRange[0]) {
        val = String(AnswerRange[0])
      }
    }
    onChange({ ...data, AnswerText: val })
    setText(val)
  }, [data, onChange, AnswerRange])

  const onFocus = () => {
    onFocusFun?.()
  }

  const onBlur = () => {
    onBlurFun?.()
  }

  useEffect(() => {
    setText(AnswerNum)
  }, [AnswerNum, setText])

  const { QuestionText, Required } = data

  return (
    <View className={styles.container}>
      <SurveyHeader
        label={QuestionText?.[language]}
        questionType={questionType}
        ordinal={ordinal}
        required={Required}
      />
      <View className={styles.inputContainer}>
        <View className={styles.inputWrap}>
          {submitted
            ? (
              <Text className={`${styles.input} ${styles.submitted}`}>
                {text || '未填写'}
              </Text>
            ) : (
              <Input
                type="number"
                placeholder="请输入"
                placeholderClass={styles.placeholderText}
                className={styles.input}
                onBlur={onBlur}
                onFocus={onFocus}
                value={text}
                onInput={onChangeText}
              />
            )}
          <Text className={styles.unit}>
            {AnswerUnit}
          </Text>
        </View>
      </View>
    </View>
  )
}

export default SurveyNumber
